<?php

namespace app\rent\controller;

use think\Controller;

class Product extends Controller
{

  public function _initialize()
  {
    parent::_initialize();
    // 实例化模型   
    $this->BusinessModel = model('Business.Business');
    $this->ProductModel = model('Product.Product');
    $this->CategoryModel = model('Category');
    $this->CollectionModel = model('Business.Collection');
  }

  // 产品列表
  public function index()
  {
    $keywords = $this->request->param('keywords', '', 'trim');

    $where = [];
    $where['status'] = '1';
    $where['rentstatus'] = ['in', '2,3'];

    if (!empty($keywords)) {
      $where['name'] = ['like', "%$keywords%"];
    }

    $data = $this->ProductModel->where($where)->order('createtime desc')->select();

    $this->success('', '', $data);
  }

  // 产品详情
  public function info()
  {
    $proid = $this->request->param('proid', 0, 'trim');
    $busid = $this->request->param('busid', 0, 'trim');

    $info = $this->ProductModel->find($proid);
    if (!$info) {
      $this->error('当前产品不存在');
    }

    $iscollect = false;
    $collect = $this->CollectionModel->where('proid', $info['id'])->find();
    if ($collect) {
      $iscollect = true;
    }
    $info['iscollect'] = $iscollect;
    $this->success('', '', $info);
  }


  // 产品收藏、取消收藏
  public function collection()
  {
    $proid = $this->request->param('proid', 0, 'trim');
    $busid = $this->request->param('busid', 0, 'trim');

    $Businessinfo = $this->BusinessModel->find($busid);
    if (!$Businessinfo) {
      $this->error('当前用户不存在');
    }

    if ($proid > 0) {
      $Cateinfo = $this->CategoryModel->find($proid);
      if (!$Cateinfo) {
        $this->error('当前产品不存在');
      }
    }

    $collectinfo = $this->CollectionModel->where(['busid' => $busid, 'proid' => $proid])->find();
    // 已经收藏
    if ($collectinfo) {
      $result = $this->CollectionModel->destroy($collectinfo['id']);
      if ($result) {
        $this->success('取消成功', '', ['collect' => false]);
      } else {
        $this->error($this->CollectionModel->getError());
      }
    } else {
      // 未收藏
      $data = [
        'busid' => $busid,
        'proid' => $proid,
      ];

      // 创建验证器对象
      $validator = new \app\common\validate\Rent\Collect();
      // 指定验证场景
      $validator->scene('product');

      // 调用验证器的check方法进行验证
      $result = $validator->check($data);
      if ($result === true) {
        // 通过验证后进行保存
        $iscollect = $this->CollectionModel->save($data);
        if ($iscollect) {
          $this->success('收藏成功', '', ['collect' => $iscollect]);
        } else {
          $this->error($this->CollectionModel->getError());
        }
      } else {
        $this->error($validator->getError());
      }
    }
  }
}
